import re
import os
import sys
import urllib
import logging

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template

import AppEnv
import Error
import models.AppConfig
import models.Theme
import lib.json

class RequestHandler(webapp.RequestHandler):
	def __init__(self):
		pass

	def initialize(self, request, response):
		webapp.RequestHandler.initialize(self, request, response)

                self.reqpath = self.request.path[len(AppEnv.apppath):]
		self.user = users.get_current_user()
		self.is_admin = users.is_current_user_admin()
                self.is_blogger = False
		if self.user:
			self.is_blogger = models.Blog.is_blogger(self.user.email())
			
		try:
			self.referer = self.request.headers['referer']
		except:
			self.referer = None

                self.appconfig = models.AppConfig.getAppConfig()
                self.appname = AppEnv.appname
		self.appversion = AppEnv.appversion
                self.apppath = AppEnv.apppath
                
                self.templatedic = {
                                     'appname': self.appname,
				     'appversion': self.appversion,
                                     'apppath': self.apppath,
                                     'appconfig': self.appconfig,
                                     'user': self.user,
                                     'is_admin': self.is_admin,
                                     'is_blogger': self.is_blogger,
                                     'referer': self.referer,
                                     }

	def param(self, name, **kw):
		tmp = self.request.get(name, **kw)
                if isinstance(tmp, unicode):
                        tmp = tmp.encode(AppEnv.appencoding)
                return tmp

	def write(self, s):
		self.response.out.write(s)

        def render(self, pageid, default=False):
		default_path = os.path.join(AppEnv.app_root, 'template', 'default', pageid)
                if default or not hasattr(self, 'theme') or not self.theme:
			# if theme not set, use default theme
                        self.templatedic['theme'] = models.Theme.getDefaultTheme()
			path = default_path
                else:
                        path = os.path.join(AppEnv.app_root, 'template', self.theme.name, pageid)
			if not os.path.exists(path):
				path = default_path
                self.write(template.render(path, self.templatedic))

        def renderErrorPage(self,msg=None,statecode=None,url=None):
                self.templatedic['errmsg'] = str(msg)
                if statecode:
                        self.error(statecode)
                if not url:
                        if self.referer:
                                url = self.referer
                        else:
                                url = AppEnv.apppath
                self.templatedic['url'] = url
                self.render(models.Theme.ShowError_page)

class PageRequestHandler(RequestHandler):
	def __init__(self):
		pass

        def handle_exception(self, exception, debug_mode):
                if isinstance(exception, Error.NoPrivilegeError):
                        self.redirect(users.create_logout_url(users.create_login_url(urllib.unquote_plus(self.request.uri))))
                        return
                if isinstance(exception, Error.PageNotFoundError)\
                   or isinstance(exception, Error.NoThisObjectError):
                        self.renderErrorPage(msg=str(exception), statecode=404)
                        return
                if debug_mode:
                        return RequestHandler.handle_exception(self, exception, debug_mode)
                self.renderErrorPage(msg='Server Internal Error\n%s'%str(exception), statecode=500)
	def initialize(self, request, response):
                RequestHandler.initialize(self, request, response)
                # the baseurl is the 
                self.templatedic['baseurl'] = 0
                self.templatedic['userbaseurl'] = 0

                if not self.user:
                    login_url = users.create_login_url(urllib.unquote_plus(self.request.uri))
                    logout_url = ''
                else:
                    login_url = ''
                    logout_url = users.create_logout_url(urllib.unquote_plus(self.request.uri))
                self.templatedic['logout_url'] = logout_url
                self.templatedic['login_url'] = login_url
                

        def renderErrorPage(self,msg=None,statecode=None,url=None):
                self.templatedic['errmsg'] = str(msg)
                if statecode:
                        self.error(statecode)
                if not url:
                        if self.referer:
                                url = self.referer
                        else:
                                url = AppEnv.apppath
                self.templatedic['url'] = url
                self.render(models.Theme.ShowError_page)

class AjaxRequestHandler(RequestHandler):
	def __init__(self):
		pass

        def handle_exception(self, exception, debug_mode):
                if isinstance(exception, Error.PageNotFoundError)\
                   or isinstance(exception, Error.NoThisObjectError):
                        self.renderErrorPage(msg='Server Internal Error\n%s'%str(exception), statecode=404)
                if debug_mode:
                        return super(RequestHandler, self).handle_exception(exception, debug_mode)
                self.renderErrorPage(msg='Server Internal Error\n%s'%str(exception), statecode=500)
		return

        def renderErrorPage(self,msg=None,statecode=None,url=None):
                self.templatedic['errmsg'] = str(msg)
                if statecode:
                        self.error(statecode)
                self.write(lib.json.write({'status':False,'errmsg':msg}))
                return
        
class HTTP404(RequestHandler):
    def get(self):
        self.renderErrorPage(Error.PageNotFoundError(),404)
    def post(self):
        return self.get()

class HTTP500(RequestHandler):
    def get(self):
        self.renderErrorPage('Server Intenal Error',500)
    def post(self):
        return self.get()

